package com.phoenix.zhihu.controller;

import com.phoenix.zhihu.entity.Arctic;
import com.phoenix.zhihu.service.ArticleService;
import com.phoenix.zhihu.service.UserService;
import com.phoenix.zhihu.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

/**
 * 上传文件本地版本
 * 注意项目路径不能有中文路径
 */
@Controller
public class ImageUploadController {
    @Autowired
    UserService userService;
    @Autowired
    ArticleService articleService;
    @RequestMapping("/upload")
    @ResponseBody
    public ImgInfo setImgUrl(MultipartFile file, HttpServletResponse response, HttpServletRequest request,Integer isDp)
            throws Exception {
        File path2 = new File(ResourceUtils.getURL("classpath:static").getPath().replace("%20"," ").replace('/', '\\'));
        System.out.println(path2);
        if(!path2.exists()) path2 = new File("");
        //如果上传目录为/static/images/upload/，则可以如下获取：
        File upload2 = new File(path2.getAbsolutePath(),"img/upfile/");
        if(!upload2.exists()) upload2.mkdirs();
        String path=upload2.getAbsolutePath()+"/";

        // Get the file and save it somewhere
        byte[] bytes = file.getBytes();
//        System.out.println(new String(bytes));
//        String path = request.getServletContext().getRealPath("/image/");
        File imgFile = new File(path);
        if (!imgFile.exists()) {
            imgFile.mkdirs();
            System.out.println("文件创建成功！");
        }
        String fileName ="";
        //获得后缀
        fileName = file.getOriginalFilename();
//        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (isDp != null||isDp==0){
             fileName = ""+userService.getNowUserId(request)+"dp.jpg";// 文件名称
        }else {
             fileName = ""+ UUID.randomUUID()+file.getOriginalFilename();// 文件名称
        }

        System.out.println(path + fileName);

        try (FileOutputStream fos = new FileOutputStream(new File(path + fileName))) {
            int len = 0;
            fos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String value = "http://localhost:8080/img/upfile/" + fileName;
        String[] values = { value };

        ImgInfo imgInfo = new ImgInfo();
        imgInfo.setError(0);
        imgInfo.setUrl(values);

        System.out.println(imgInfo.toString());
        return imgInfo;
    }

    @RequestMapping("/upload_dp")
    @ResponseBody
    public ImgInfo upload_dp(MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception {
        ImgInfo imgInfo = setImgUrl(file,response,request,1);
        Cookie[] cookies = request.getCookies();
        int userid = Integer.parseInt(CookieUtil.getValue(cookies,"zhihuid"));
        userService.addUserImage(userid,imgInfo.getUrl()[0]);
        return  imgInfo;
    }




}